package com.xinyiweidai.xinyiweidai.module.login;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lan.mylibrary.okhttp.L;
import com.lan.mylibrary.okhttp.OkHttpUtils;
import com.lan.mylibrary.okhttp.callback.StringCallback;
import com.lan.mylibrary.ui.MyTitle;
import com.lan.mylibrary.ui.MyToast;
import com.xinyiweidai.xinyiweidai.BuildConfig;
import com.xinyiweidai.xinyiweidai.Constants;
import com.xinyiweidai.xinyiweidai.R;
import com.xinyiweidai.xinyiweidai.base.BaseActivity;
import com.xinyiweidai.xinyiweidai.bean.LoginBean;
import com.xinyiweidai.xinyiweidai.util.Api;
import com.xinyiweidai.xinyiweidai.util.LoginUtil;
import com.xinyiweidai.xinyiweidai.util.SpUtil;
import java.util.HashMap;
import java.util.Map;
import okhttp3.Request;

/**
* 项目名：com.xinyiweidai.xinyiweidai
* 类名： LoginActivity
* 创建人：Lan
* 创建时间：2018/9/8 19:06
* 描述：  登录界面
*/
public class LoginActivity extends BaseActivity {


    private CheckBox checkBox_login;
    private EditText et_login_number;
    private EditText et_login_password;
    private TextView tv_login_register;
    private TextView tv_login_forget;
    private TextView tv_agreement;
    private Button btn_login;



    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }


    @Override
    protected void initToolBar() {
        new MyTitle(this, R.drawable.ic_back,"登录",0,true);
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        et_login_number = (EditText) findViewById(R.id.et_login_number);
        et_login_password = (EditText) findViewById(R.id.et_login_password);
        tv_login_register = (TextView) findViewById(R.id.tv_login_register);
        tv_login_forget = (TextView) findViewById(R.id.tv_login_forget);
        tv_agreement = (TextView) findViewById(R.id.tv_agreement);
        btn_login = (Button) findViewById(R.id.btn_login);
        checkBox_login = (CheckBox) findViewById(R.id.checkBox_login);

        checkPermisson();
    }

    private void checkPermisson() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        } else {
            LoginUtil.initLocation(this);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    LoginUtil.initLocation(this);
                } else {
                    Toast.makeText(this, "必须授权才能登陆", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }
    }


    @Override
    protected void addClickEvent() {
        btn_login.setOnClickListener(view -> checkLogin());
        tv_agreement.setOnClickListener(view -> startNewActivity(UserAgreementActivity.class));
        tv_login_register.setOnClickListener(view -> startActivityForResult(new Intent(this,RegisterActivity.class),1));
        tv_login_forget.setOnClickListener(view -> startActivityForResult(new Intent(this,ResetPasswordActivity.class),2));
    }


    private void checkLogin() {
        String number=et_login_number.getText().toString();
        String password=et_login_password.getText().toString();
        if (TextUtils.isEmpty(number)||TextUtils.isEmpty(password)) {
            MyToast.showError(this,"输入有误");
            return;
        }
        if (!checkBox_login.isChecked()){
            MyToast.showError(this,"请勾选协议");
            return;
        }
        Log.e("222", LoginUtil.longitude + "  " + LoginUtil.latitude + "  " + LoginUtil.getMacAddr()+ "  " + android.os.Build.MODEL + "-" + android.os.Build.VERSION.RELEASE+ "-" + BuildConfig.VERSION_NAME);
        Map<String, String> map = new HashMap<>();
        map.put("account", number);
        map.put("password", password);
        //新加参数
        map.put("mac_address", LoginUtil.getMacAddr());
        map.put("jingdu", LoginUtil.longitude + "");
        map.put("weidu", LoginUtil.latitude + "");
        map.put("mobile_type", android.os.Build.MODEL + "-" + android.os.Build.VERSION.RELEASE);
        map.put("mobile_type_version", BuildConfig.VERSION_NAME+"测试");
        goLogin(map);
    }


    private void goLogin(Map<String, String> map) {
        showLoading("正在登录");
        OkHttpUtils.get().url(Api.login).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                dismissLoading();
                MyToast.showError(LoginActivity.this,"网络异常");
            }

            @Override
            public void onResponse(String response) {
                L.e(response);
                dismissLoading();
                parseData(response);
            }
        });
    }


    private void parseData(String response) {
        LoginBean bean=new Gson().fromJson(response,LoginBean.class);
        if (bean.getCode()==1){
            Constants.isLogin=true;
            MyToast.showSuccess(LoginActivity.this,"登陆成功");
            SpUtil.getInstance().saveUserInfo(bean.getData().getUserinfo());
            SpUtil.getInstance().saveBoolean("isAutoLogin",true);
            setResult(102);
            finish();
        }else{
            MyToast.showError(LoginActivity.this,bean.getMsg());
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode==RESULT_OK){
            et_login_number.setText(data.getStringExtra("mobile"));
            et_login_password.requestFocus();
        }
    }
}
